package com.uenpay.im.ui.old.activity.movement;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aswife.ui.MaskImageView;
import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qiyunxin.android.http.listener.OnUploadFileListener;
import com.qiyunxin.android.http.net.HttpRequestAsyncTaskQueue;
import com.qiyunxin.android.http.net.HttpUploadFileAsyncTask;
import com.qiyunxin.android.http.utils.FileUtils;
import com.qyx.android.weight.choosemorepic.PhotoItem;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.area.AreaActivity;
import com.uenpay.im.ui.old.activity.choosemorepic.PhotoActivity;
import com.uenpay.im.ui.old.activity.choosemorepic.TakePhotoActivity;
import com.uenpay.im.callback.IDateDailogListener;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.ImageSize;
import com.uenpay.im.weight.BottomDialog;
import com.uenpay.im.weight.MyMinuteDateDialog;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

/**
 * @author SL
 * @created 2016-1-21 10:56:14
 * @copyRight http://www.qiyunxin.com
 * @function TODO
 */
public class PublishMovementActivity extends BaseActivity {

    private final int CHOOSE_TAKE_PHOTO_REQUEST_CODE = 110;
    private final int CHOOSE_IMAGE_REQUEST_CODE = 111;
    private MaskImageView movement_cover_iv;
    private TextView movement_title_tv, movement_date_tv, movement_address_tv,
            movement_num_tv, movement_introduce_tv, movement_cost_tv,
            movement_specific_address_tv;
    private RelativeLayout cover_layout, movement_title_layout,
            movement_date_layout, movement_num_layout, movement_address_layout,
            movement_cost_layout, movement_introduce_layout,
            movement_specific_address_layout;
    private Button submit_btn;
    private byte[] coverByte = null;
    private FileUtils fileUtils = new FileUtils(IMApplication.appName);
    private String title, date, address, num, introduce, cost, picPath;
    private View loading;
    private MovementHandler movementHandler = new MovementHandler();
    private int movementId = 0;
    private String fileid = "", filehash = "";
    private String movementFree = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_publish_movement_layout;
    }

    @Override
    public void initView(View view) {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.movement_publish_movement));
        movement_cover_iv = (MaskImageView) findViewById(R.id.movement_cover_iv);
        movement_title_tv = (TextView) findViewById(R.id.movement_title_tv);
        movement_date_tv = (TextView) findViewById(R.id.movement_date_tv);
        movement_address_tv = (TextView) findViewById(R.id.movement_address_tv);
        movement_num_tv = (TextView) findViewById(R.id.movement_num_tv);
        movement_introduce_tv = (TextView) findViewById(R.id.movement_introduce_tv);
        movement_cost_tv = (TextView) findViewById(R.id.movement_cost_tv);
        movement_specific_address_tv = (TextView) findViewById(R.id.movement_specific_address_tv);
        cover_layout = (RelativeLayout) findViewById(R.id.cover_layout);
        movement_title_layout = (RelativeLayout) findViewById(R.id.movement_title_layout);
        movement_date_layout = (RelativeLayout) findViewById(R.id.movement_date_layout);
        movement_num_layout = (RelativeLayout) findViewById(R.id.movement_num_layout);
        movement_address_layout = (RelativeLayout) findViewById(R.id.movement_address_layout);
        movement_cost_layout = (RelativeLayout) findViewById(R.id.movement_cost_layout);
        movement_introduce_layout = (RelativeLayout) findViewById(R.id.movement_introduce_layout);
        movement_specific_address_layout = (RelativeLayout) findViewById(R.id.movement_specific_address_layout);
        loading = findViewById(R.id.loading);
        submit_btn = (Button) findViewById(R.id.submit_btn);
    }

    private void initData() {
        if (getIntent() != null && getIntent().hasExtra("movementId")) {
            movementId = getIntent().getIntExtra("movementId", 0);
            movement_title_tv.setText(getIntent().getStringExtra(
                    "movementTitle"));
            movement_date_tv.setText(getIntent().getStringExtra(
                    "movementCreateTime"));
            movement_address_tv.setText(getIntent().getStringExtra(
                    "movementAddress"));
            movement_introduce_tv.setText(getIntent().getStringExtra(
                    "movementDescription"));
            movement_cost_tv.setText(getIntent().getStringExtra("movementFee"));
            movement_num_tv.setText(getIntent().getIntExtra(
                    "movementPersonNum", 0)
                    + "");
            fileid = getIntent().getStringExtra("movementCoverFileId");
            filehash = getIntent().getStringExtra("movementCoverFileHash");
            movement_cover_iv.SetUrl(APIConfiguration.getFileDownloadPath(
                    fileid, filehash));
            ((TextView) findViewById(R.id.title_textview))
                    .setText(getResources().getString(
                            R.string.movement_edit_movement));
            submit_btn.setText(R.string.movement_update);
            submit_btn.setBackgroundResource(R.drawable.button_bg_normal);
            submit_btn.setEnabled(true);
        }

    }

    protected void initListener() {
        cover_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                chooseCoverDialog();

            }
        });
        movement_specific_address_layout
                .setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        Intent intent = new Intent(
                                PublishMovementActivity.this,
                                EditMovementActivity.class);
                        intent.putExtra(
                                "update_type",
                                UpdateMovementField.UPDATE_MOVEMENT_SPECIFIC_ADDRESS);
                        intent.putExtra("oldStr", movement_specific_address_tv
                                .getText().toString());
                        startActivityForResult(
                                intent,
                                UpdateMovementField.UPDATE_MOVEMENT_SPECIFIC_ADDRESS);

                    }
                });
        movement_title_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(PublishMovementActivity.this,
                        EditMovementActivity.class);
                intent.putExtra("update_type",
                        UpdateMovementField.UPDATE_MOVEMENT_TITLE);
                intent.putExtra("oldStr", movement_title_tv.getText()
                        .toString());
                startActivityForResult(intent,
                        UpdateMovementField.UPDATE_MOVEMENT_TITLE);
            }
        });
        movement_date_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                setMovementDate();
            }
        });
        movement_num_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(PublishMovementActivity.this,
                        EditMovementActivity.class);
                intent.putExtra("update_type",
                        UpdateMovementField.UPDATE_MOVEMENT_NUM);
                intent.putExtra("oldStr", movement_num_tv.getText().toString());
                startActivityForResult(intent,
                        UpdateMovementField.UPDATE_MOVEMENT_NUM);
            }
        });
        movement_address_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(PublishMovementActivity.this,
                        AreaActivity.class);

                // Intent intent = new Intent(PublishMovementActivity.this,
                // EditMovementActivity.class);
                // intent.putExtra("update_type",
                // UpdateMovementField.UPDATE_MOVEMENT_ADDRESS);
                // intent.putExtra("oldStr", movement_address_tv.getText()
                // .toString());
                startActivityForResult(intent,
                        UpdateMovementField.UPDATE_MOVEMENT_ADDRESS);
            }
        });
        movement_cost_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(PublishMovementActivity.this,
                        EditMovementActivity.class);
                intent.putExtra("update_type",
                        UpdateMovementField.UPDATE_MOVEMENT_COST);
                intent.putExtra("oldStr", movementFree);
                startActivityForResult(intent,
                        UpdateMovementField.UPDATE_MOVEMENT_COST);
            }
        });
        movement_introduce_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(PublishMovementActivity.this,
                        EditMovementActivity.class);
                intent.putExtra("update_type",
                        UpdateMovementField.UPDATE_MOVEMENT_INTRO);
                intent.putExtra("oldStr", movement_introduce_tv.getText()
                        .toString());
                startActivityForResult(intent,
                        UpdateMovementField.UPDATE_MOVEMENT_INTRO);
            }
        });

        submit_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (!TextUtils.isEmpty(picPath)) {
                    String url = APIConfiguration.getBaseUrl()
                            + "Activity/Activity/sendFile?"
                            + APIConfiguration.getCustIdAndToken();
                    uploadCover(url);
                } else {
                    publishMovement();
                }
            }
        });

    }

    private void uploadCover(String url) {

        loading.setVisibility(View.VISIBLE);
        if (picPath.startsWith("http")) {
            picPath = HttpStreamCache.getInstance().GetFilePath(picPath);
        }
        HttpRequestAsyncTaskQueue.getInstance().AddTask(
                new HttpUploadFileAsyncTask("1", picPath, url, "uploadedFile") {

                }, new OnUploadFileListener() {

                    @Override
                    public void OnSuccess(String key, String response) {
                        JSONObject json;
                        try {
                            json = new JSONObject(response);
                            try {
                                int status = json.optInt("status");
                                String msg = json.optString("msg");
                                JSONObject dataJson = json
                                        .optJSONObject("data");
                                if (status == HttpInvokeResultCode.RESULT_OK
                                        && dataJson != null) {
                                    if (dataJson.has("fileid")
                                            && dataJson.has("filehash")) {
                                        fileid = dataJson.optString("fileid");
                                        filehash = dataJson
                                                .optString("filehash");
                                        publishMovement();
                                    } else {
                                        IMApplication.showToast(msg);
                                        myHandler.sendEmptyMessage(1);
                                    }

                                } else {
                                    IMApplication.showToast(msg);
                                    myHandler.sendEmptyMessage(1);
                                }

                            } catch (Exception e) {
                            }
                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }

                    @Override
                    public void OnFail(String key, String reason) {
                        IMApplication.showToast(reason);
                        myHandler.sendEmptyMessage(1);
                    }
                });

    }

    private void publishMovement() {
        String specific_address = movement_specific_address_tv.getText()
                .toString();
        if (!TextUtils.isEmpty(specific_address)) {
            address = address + specific_address;
        }
        movementHandler.publishMovement(movementId, title, date, date, num,
                address, cost, introduce, fileid, filehash,
                new MovementHandler.IResultListener() {

                    @Override
                    public void onResult(int status, String msg) {
                        myHandler.sendEmptyMessage(1);
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            sendBroadcast(new Intent(
                                    BroadcastAction.ACTION_REFRESH_MOVEMENT));
                            if (movementId != 0) {
                                setResult(RESULT_OK);
                            }
                            finish();
                        } else {
                            IMApplication.showToast(msg);
                        }
                    }
                });
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message arg0) {
            if (arg0.what == 1) {
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            }
            return false;
        }
    });

    private void chooseCoverDialog() {

        BottomDialog.showBottomDialog(PublishMovementActivity.this,
                getResources().getString(R.string.take_photo), getResources()
                        .getString(R.string.take_image), getResources()
                        .getString(R.string.cancel), -1,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        takePhoto();
                    }
                }, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        pickImage();
                    }
                });

    }

    private void takePhoto() {
        Intent getImageByCamera = new Intent(PublishMovementActivity.this,
                TakePhotoActivity.class);
        ArrayList<ImageSize> size = new ArrayList<ImageSize>();
        size.add(new ImageSize(960, 960, ""));

        Bundle bundle = new Bundle();
        bundle.putSerializable("size", size);
        getImageByCamera.putExtras(bundle);
        startActivityForResult(getImageByCamera, CHOOSE_TAKE_PHOTO_REQUEST_CODE);
    }

    private void pickImage() {
        Intent getImage = new Intent(PublishMovementActivity.this,
                PhotoActivity.class);
        getImage.putExtra("selected_count", 0);
        getImage.putExtra("max_select_count", 1);

        startActivityForResult(getImage, CHOOSE_IMAGE_REQUEST_CODE);
    }

    private void setMovementDate() {
        int selectedYear = -1;
        int selectedMonth = -1;
        int selectedDay = -1;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",
                Locale.getDefault());
        if (!TextUtils.isEmpty(movement_date_tv.getText().toString())) {
            Calendar calendar = Calendar.getInstance();

            try {
                String str = String.valueOf(sdf.parse(
                        movement_date_tv.getText().toString()).getTime());
                calendar.setTimeInMillis(Long.valueOf(str));
                selectedYear = calendar.get(Calendar.YEAR);
                selectedMonth = calendar.get(Calendar.MONDAY);
                selectedDay = calendar.get(Calendar.DAY_OF_MONTH);
            } catch (java.text.ParseException e) {
                e.printStackTrace();
            }

        }
        MyMinuteDateDialog dateDialog = new MyMinuteDateDialog(selectedYear,
                selectedMonth, selectedDay, PublishMovementActivity.this,
                new IDateDailogListener() {

                    @Override
                    public void OnDailogChick(String year, String Month,
                                              String Day, String minute, String second) {
                        movement_date_tv.setText(year + "-" + Month + "-" + Day
                                + "-" + minute + "-" + second);
                        checkBtnStatus();
                    }
                });
        dateDialog.showDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == CHOOSE_IMAGE_REQUEST_CODE) {
            @SuppressWarnings("unchecked")
            ArrayList<PhotoItem> select_gl_arr = (ArrayList<PhotoItem>) data
                    .getSerializableExtra("gl_arr");
            if (select_gl_arr.size() > 0) {
                for (int i = 0; i < select_gl_arr.size(); i++) {
                    picPath = select_gl_arr.get(i).getPath();
                    movement_cover_iv.SetUrl(picPath);
                    coverByte = fileUtils.getBytesFromFile(new File(picPath));
                }
            }

        } else if (requestCode == CHOOSE_TAKE_PHOTO_REQUEST_CODE) {
            picPath = data.getStringExtra("big_pic_filename");
            movement_cover_iv.SetUrl(picPath);
            coverByte = fileUtils.getBytesFromFile(new File(picPath));
        } else if (requestCode == UpdateMovementField.UPDATE_MOVEMENT_TITLE) {
            movement_title_tv.setText(data.getStringExtra("result"));
        } else if (requestCode == UpdateMovementField.UPDATE_MOVEMENT_NUM) {
            movement_num_tv.setText(data.getStringExtra("result"));
        } else if (requestCode == UpdateMovementField.UPDATE_MOVEMENT_ADDRESS) {
            movement_address_tv.setText(data.getStringExtra("result"));
        } else if (requestCode == UpdateMovementField.UPDATE_MOVEMENT_COST) {
            double fee = Double.valueOf(data.getStringExtra("result"));
            if (fee <= 0) {
                movement_cost_tv.setText(R.string.movement_free_charge);
            } else {
                movement_cost_tv.setText(data.getStringExtra("result"));
            }
            movementFree = data.getStringExtra("result");
        } else if (requestCode == UpdateMovementField.UPDATE_MOVEMENT_INTRO) {
            movement_introduce_tv.setText(data.getStringExtra("result"));
        } else if (requestCode == UpdateMovementField.UPDATE_MOVEMENT_SPECIFIC_ADDRESS) {
            movement_specific_address_tv.setText(data.getStringExtra("result"));
        }
        checkBtnStatus();
    }

    private void checkBtnStatus() {
        title = movement_title_tv.getText().toString();
        num = movement_num_tv.getText().toString();
        address = movement_address_tv.getText().toString();
        // cost = movement_cost_tv.getText().toString();
        cost = movementFree;
        introduce = movement_introduce_tv.getText().toString();
        date = movement_date_tv.getText().toString();
        if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(num)
                && !TextUtils.isEmpty(address) && !TextUtils.isEmpty(cost)
                && !TextUtils.isEmpty(introduce)
                && (coverByte != null || movementId != 0)) {
            submit_btn.setBackgroundResource(R.drawable.button_bg_normal);
            submit_btn.setEnabled(true);
        } else {
            submit_btn.setEnabled(false);
            submit_btn.setBackgroundResource(R.drawable.button_bg_gray);
        }
    }

}
